// 获取DOM元素
const uploadArea = document.getElementById('uploadArea');
const imageInput = document.getElementById('imageInput');
const uploadOverlay = document.getElementById('uploadOverlay');
const uploadedImg = document.getElementById('uploadedImg');
const analyzeBtn = document.getElementById('analyzeBtn');
const resetBtn = document.getElementById('resetBtn');
const errorMessage = document.getElementById('errorMessage');
const successMessage = document.getElementById('successMessage');
const analysisPlaceholder = document.getElementById('analysisPlaceholder');
const loadingState = document.getElementById('loadingState');
const analysisResult = document.getElementById('analysisResult');
const progressFill = document.getElementById('progressFill');

let uploadedFile = null;

// 文件大小格式化
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示错误消息
function showError(message) {
    errorMessage.textContent = message;
    errorMessage.style.display = 'block';
    successMessage.style.display = 'none';
    setTimeout(() => {
        errorMessage.style.display = 'none';
    }, 5000);
}

// 显示成功消息
function showSuccess(message) {
    successMessage.textContent = message;
    successMessage.style.display = 'block';
    errorMessage.style.display = 'none';
    setTimeout(() => {
        successMessage.style.display = 'none';
    }, 3000);
}

// 验证文件
function validateFile(file) {
    const maxSize = 10 * 1024 * 1024; // 10MB
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];

    if (!allowedTypes.includes(file.type)) {
        throw new Error('不支持的文件格式，请选择 JPG、PNG 或 GIF 格式的图片');
    }

    if (file.size > maxSize) {
        throw new Error('文件大小超过限制，请选择小于 10MB 的图片');
    }

    return true;
}

// 处理文件上传
function handleFile(file) {
    try {
        validateFile(file);

        const reader = new FileReader();
        reader.onload = function (e) {
            // 显示上传的图片
            uploadedImg.src = e.target.result;

            // 显示覆盖界面
            uploadOverlay.classList.add('active');

            // 启用分析按钮
            analyzeBtn.disabled = false;

            // 保存文件
            uploadedFile = file;

            showSuccess('图片上传成功！');
        };
        reader.readAsDataURL(file);

    } catch (error) {
        showError(error.message);
    }
}

// 点击上传区域
uploadArea.addEventListener('click', () => {
    imageInput.click();
});

// 文件选择
imageInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
        handleFile(file);
    }
});

// 拖拽上传
uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');

    const files = e.dataTransfer.files;
    if (files.length > 0) {
        handleFile(files[0]);
    }
});

// 重新选择按钮
resetBtn.addEventListener('click', () => {
    // 重置所有状态
    uploadOverlay.classList.remove('active');
    imageInput.value = '';
    uploadedFile = null;
    analyzeBtn.disabled = true;

    // 隐藏结果区域
    analysisPlaceholder.style.display = 'block';
    loadingState.style.display = 'none';
    analysisResult.style.display = 'none';

    // 隐藏消息
    errorMessage.style.display = 'none';
    successMessage.style.display = 'none';
});

// 分析按钮
analyzeBtn.addEventListener('click', async () => {
    if (!uploadedFile) {
        showError('请先上传图片');
        return;
    }

    // 显示加载状态
    analysisPlaceholder.style.display = 'none';
    loadingState.style.display = 'block';
    analysisResult.style.display = 'none';

    // 禁用按钮
    analyzeBtn.disabled = true;

    // 模拟进度条
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        progressFill.style.width = progress + '%';
    }, 300);

    try {
        // 创建FormData
        const formData = new FormData();
        formData.append('image', uploadedFile);

        // 发送请求到后端
        const response = await fetch('/picture/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
            },
            body: formData,
            credentials: 'include',
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // 完成进度条
        clearInterval(progressInterval);
        progressFill.style.width = '100%';

        // 延迟显示结果( 10s )
        setTimeout(() => {
            displayAnalysisResult(data);
            loadingState.style.display = 'none';
            analysisResult.style.display = 'block';
        }, 1000);

    } catch (error) {
        clearInterval(progressInterval);
        console.error('分析请求失败:', error);

        // // 模拟分析结果（用于演示）
        // setTimeout(() => {
        //     const mockData = {
        //         success: true,
        //         results: [
        //             {
        //                 type: 'content_detection',
        //                 title: '图片内容识别',
        //                 content: '检测到图片包含：人物、建筑、文字等元素',
        //                 risk_level: 'low'
        //             },
        //             {
        //                 type: 'safety_check',
        //                 title: '心理状态检测',
        //                 content: '图片内容安全，未发现违规内容',
        //                 risk_level: 'low'
        //             },
        //             {
        //                 type: 'quality_analysis',
        //                 title: '心理质量分析',
        //                 content: '图片清晰度良好，色彩饱和度适中',
        //                 risk_level: 'high'
        //             }
        //         ]
        //     };
        //
        //     progressFill.style.width = '100%';
        //     displayAnalysisResult(mockData);
        //     loadingState.style.display = 'none';
        //     analysisResult.style.display = 'block';
        // }, 2000);
    } finally {
        analyzeBtn.disabled = false;
    }
});

// 显示分析结果
function displayAnalysisResult(data) {
    if (!data.success) {
        showError(data.message || '分析失败，请重试');
        return;
    }

    let resultHTML = '';
    if (data.results && data.results.length > 0) {
        data.results.forEach(result => {
            const riskClass = `risk-${result.risk_level}`;
            const riskText = {
                'low': '低风险',
                'medium': '中风险',
                'high': '高风险'
            }[result.risk_level] || '未知';

            resultHTML += `
                        <div class="result-card">
                            <div class="result-title">
                                ${getResultIcon(result.type)} ${result.title}
                                <span class="risk-level ${riskClass}">${riskText}</span>
                            </div>
                            <div class="result-content">${result.content}</div>
                        </div>
                    `;
        });
    } else {
        resultHTML = `
                    <div class="result-card">
                        <div class="result-title">
                            ℹ️ 分析完成
                        </div>
                        <div class="result-content">图片分析完成，未发现特殊内容。</div>
                    </div>
                `;
    }

    analysisResult.innerHTML = resultHTML;
}

// 获取结果图标
function getResultIcon(type) {
    const icons = {
        'content_detection': '🔍',
        'safety_check': '🛡️',
        'quality_analysis': '📊',
        'text_recognition': '📝',
        'object_detection': '🎯'
    };
    return icons[type] || '📋';
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
